import React, { useEffect, useRef, useState } from 'react'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { Button, Table, Tag, Modal, Popover, Switch } from 'antd'
import { connect } from 'umi'
import _ from 'lodash'

function RightList(props: any) {
    // props中解构出 dispatch 和 routeList 属性
    // 存储权限列表
    const { dispatch, routeList } = props;
    // 存储调整后（children长度为0，设为null）的权限列表
    const [limits, setLimits] = useState(routeList)
    // 表格的loading
    const [loading, setLoading] = useState(false);
    // 删除按钮对话框是否显示，初始为false，不显示
    const [deleteOpen, setDeleteOpen] = useState(false);
    //删除对话框的异步操作等待的loading
    const [DelConfirmLoading, setDelConfirmLoading] = useState(false);
    // 保存选中的item数据
    const [currentItem, setCurrentItem] = useState(null);
    // 从本地存储中获取当前用户信息
    const currentUserData:Array<any>=JSON.parse(localStorage.getItem('token') as string) 
    useEffect(() => {
        if (routeList.length === 0) {
            dispatch({
                type: 'StandBox/getRouteList',
                payload: {}
            })
        }
        else {
            console.log('读缓存信息,routeList:', routeList);
            setLimits(adjustRouteList(routeList));
        }
    }, [routeList])

    //对redux中公共状态routeList路由配置信息进行调整，删除children长度为0，设置为null
    const adjustRouteList = (routeList: Array<any>) => {
        return routeList.map(item => {
            // console.log(item)
            if (item.children?.length === 0) {
                item.children = null
            }
            if (item.children?.length > 0) {
                // console.log('子',adjustRouteList(item.children))
                item.children = adjustRouteList(item.children)
            }
            return item
        })
    }
    //表格中删除按钮，删除对应的路由配置信息
    const handelDeleteLimit = (item: any) => {
        // 显示表格loading
        setLoading(true);
        // 显示删除对话框异步操作loading
        setDelConfirmLoading(true);
        // 删除路由对应信息
        handleDeleteConfirm(item);
    }
    //删除对应的路由配置信息，递归函数
    const deleteLimits = (dataSource: Array<any>, dataItem: { id: number }) => {
        const { id } = dataItem;
        return dataSource.filter((item: any) => {
            if (item.children?.length > 0) {
                item.children = deleteLimits(item.children, dataItem)
            }
            return item.id !== id
        })
    }
    // 删除对话框的确认，执行回调函数
    const handleDeleteConfirm = (item: any) => {
        // 当前页面同步状态+后台同步
        dispatch({
            type: 'StandBox/deleteRouteList',
            payload: {
                routeItem: item,
                setLoading,
                setDeleteOpen,
                setDelConfirmLoading,
                routes: limits
            }
        })
    }
    // 删除对话框的取消，执行回调函数
    const handleDeleteCancel = () => {
        console.log('取消操作');
        // 取消操作，关闭删除对话框
        setDeleteOpen(false)

    }
    // 开关按钮（Switch）点击事件，修改pagepermisson的值
    const handelChangePermisson = async(item: any) => {
        const newItem = _.cloneDeep(item);
        newItem.pagepermisson = newItem.pagepermisson === 1 ? 0 : 1;
        console.log(newItem.pagepermisson);
        // 本地页面同步状态+后台同步
        await dispatch({
            type: 'StandBox/modifyRouteList',
            payload: {
                routeItem: newItem,
                routes: limits
            }
        })
        // 获取最新的用户信息，避免重复登录
        if(currentUserData.length>0){
            // 获取最新的用户信息数据
            await dispatch({
                type: 'StandBox/getCurrentUserData',
                payload: {
                    currentItem:currentUserData[0],
                }
            })
            dispatch({
                type: 'StandBox/getRightList',
                payload: {}
            })
            dispatch({
                type: 'StandBox/getChildrenList',
                payload: {}
            })
        }
    }
    //表格列的配置描述
    const columns = [
        {
            title: 'ID',    //标题
            dataIndex: 'id',     //匹配的字段名 
            key: 'id',
            render: (id: string) => {
                return <b>{id}</b>
            }
        },
        {
            title: '权限名称',
            dataIndex: 'label',
            key: 'label',
        },
        {
            title: '权限路径',
            dataIndex: 'key',
            key: 'key',
            render: (key: string) => {
                return <Tag color='orange'>{key}</Tag>
            }
        },
        {
            title: '操作',
            render: (item: any) => {
                return (<div>
                    <>
                        <Button danger shape="circle" style={{ 'marginRight': '10px' }} icon={<DeleteOutlined />} onClick={() => {
                            setCurrentItem(item);
                            setDeleteOpen(true);
                        }}></Button>
                    </>
                    <Popover content={<Switch checkedChildren="开启" unCheckedChildren="关闭"
                        checked={item.pagepermisson} onClick={() => { handelChangePermisson(item) }} />}
                        title="路由配置项" trigger={item.pagepermisson === undefined ? '' : "click"}>
                        <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.pagepermisson === undefined}>
                        </Button>
                    </Popover>
                </div>)
            }
        },
    ];

    return (
        <div>
            <Table dataSource={limits} columns={columns} loading={loading} sticky scroll={{ y: '63vh' }} />
            {/* 删除的对话框 */}
            <Modal
                title={`【${(currentItem as any)?.label}】删除`}
                open={deleteOpen}
                onOk={() => { handelDeleteLimit(currentItem) }}
                confirmLoading={DelConfirmLoading}
                // mask={false}
                onCancel={handleDeleteCancel}
                okText='确定'
                cancelText='取消'
            >
                <p>是否要删除该路由</p>
            </Modal>
        </div>
    )
}

const mapStateToProps = (state: any) => {
    return {
        routeList: state.StandBox.routeList,
    }
}
export default connect(mapStateToProps)(RightList)
